package com.ruoyi.project.wx.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.shop.domain.ShopShopDO;
import com.ruoyi.project.shop.service.ShopShopService;
import com.ruoyi.project.wx.domain.GoodsGoodsDO;
import com.ruoyi.project.wx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 商品
 * 
 * @author sys
 * @email 1992lcg@163.com
 * @date 2019-03-19 16:39:22
 */
 
@Controller
@RequestMapping("/wx/wxGoodsGoods")
public class GoodsGoodsController extends BaseController {
	@Autowired
	private GoodsGoodsService goodsGoodsService;
	@Autowired
	private ShopShopService shopShopService;
	@Autowired
	private GoodsTypeService goodsTypeService;
	@Autowired
	private GoodsClassService goodsClassService;
	@Autowired
	private GoodsSpecService goodsSpecService;
	@Autowired
	private GoodsTypeParamgService goodsTypeParamgService;
	@Autowired
	private GoodsTypePropsService goodsTypePropsService;
	@Autowired
	private GoodsTypeBrandService goodsTypeBrandService;
	@Autowired
	private GoodsTypeSpecService goodsTypeSpecService;
	@Autowired
	private GoodsProductService goodsProductsService;
	@Autowired
	private GoodsImagesService goodsImagesService;
	@Autowired
	private GoodsBrandService goodsBrandService;
	@Autowired
	private GoodsTagService goodsTagService;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	@Autowired
	private SetImageUploadService setImageUploadService;
	@Autowired
	private OrderComentService orderComentService;


	/**
	 * 查询商品列表
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxGoodsGoods:list')")
	@GetMapping("/list")
	public TableDataInfo list(GoodsGoodsDO goodsGoods)
	{
		startPage();
		Map<String, Object> stringObjectMap = BeanUtil.beanToMap(goodsGoods);
		stringObjectMap.put("delFlag","0");
		stringObjectMap.put("sort","gmt_create");
		stringObjectMap.put("order","desc");
		List<GoodsGoodsDO> list = goodsGoodsService.list(stringObjectMap);
		if(list.size()>0){
			for (GoodsGoodsDO goodsGoodsDO : list) {
				ShopShopDO shopShopDO = shopShopService.get(goodsGoodsDO.getShopId());
				goodsGoodsDO.setShopId(shopShopDO.getName());
			}
		}
		return getDataTable(list);
	}

	/**
	 * 导出商品列表
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxGoodsGoods:export')")
	@Log(title = "商品", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(GoodsGoodsDO goodsGoods)
	{
		Map<String, Object> stringObjectMap = BeanUtil.beanToMap(goodsGoods);
		List<GoodsGoodsDO> list = goodsGoodsService.list(stringObjectMap);
		ExcelUtil<GoodsGoodsDO> util = new ExcelUtil<GoodsGoodsDO>(GoodsGoodsDO.class);
		return util.exportExcel(list, "wxGoodsGoods");
	}

	/**
	 * 获取商品详细信息
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxGoodsGoods:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") String id)
	{
		return AjaxResult.success(goodsGoodsService.get(id));
	}

	/**
	 * 新增商品
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxGoodsGoods:add')")
	@Log(title = "商品", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody GoodsGoodsDO goodsGoods)
	{
		goodsGoods.setId(IdUtil.simpleUUID());
		goodsGoods.setDelFlag(0);
		goodsGoods.setGmtCreate(new Date());
		return toAjax(goodsGoodsService.save(goodsGoods));
	}

	/**
	 * 修改商品
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxGoodsGoods:edit')")
	@Log(title = "商品", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody GoodsGoodsDO goodsGoods)
	{
		goodsGoods.setUpAt(new Date());
		return toAjax(goodsGoodsService.update(goodsGoods));
	}

	/**
	 * 删除商品
	 */
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('wx:wxGoodsGoods:remove')")
	@Log(title = "商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable String[] ids)
	{
		if(ids.length>0){
			for (String string : ids) {
				GoodsGoodsDO goodsGoods = goodsGoodsService.get(string);
				goodsGoods.setDelFlag(1);
				goodsGoods.setUpAt(new Date());
				goodsGoodsService.update(goodsGoods);
			}
		}
		return toAjax(ids.length);
		//return toAjax(goodsGoodsService.deleteGoodsGoodsByIds(ids));
	}


	
	/*@GetMapping()
	@RequiresPermissions("wx:goodsGoods:goodsGoods")
	String GoodsGoods(){
	    return "wx/goodsGoods/goodsGoods";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wx:goodsGoods:goodsGoods")
	public PageUtils list(@RequestParam Map<String, Object> params){
		
		Map<String, Object> map1 = new HashMap<>();
		map1.put("delFlag", 0);
		List<GoodsGoodsDO> list = goodsGoodsService.list(map1);
		List<GoodsGoodsDO> goodsGoodsList ;
		int total = 0;
		if(params.containsKey("name")&& StringUtils.isNotBlank(params.get("name").toString())){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", params.get("name").toString());
			goodsGoodsList = goodsGoodsService.list(map);
			total=goodsGoodsList.size();
		}else{
			 Query query = new Query(params);
			 goodsGoodsList = goodsGoodsService.list(query);
			 total = goodsGoodsService.count(query);
		}
		//查询列表数据
		PageUtils pageUtils = new PageUtils(goodsGoodsList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:goodsGoods:add")
	String add(Model model){
		Map<String,Object> map = new HashMap<String,Object>();
		model.addAttribute("typeList",goodsTypeService.queryAll());
	    return "wx/goodsGoods/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String edit(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
	*//*	Map<String, Object> par = new HashMap<>();
		par.put("goodsId", goodsGoods.getId());
		List<GoodsProductDO> list2 = goodsProductsService.list(par);
		for (GoodsProductDO goodsProductDO : list2) {
			if(goodsProductDO.get){
				
			}
		}*//*
		//轮播图
		Map<String, Object> imgMap = new HashMap<>();
		imgMap.put("goodsId", id);
		imgMap.put("address", "0");
		List<GoodsImagesDO> bannerList = goodsImagesService.list(imgMap);
		goodsGoods.setBanners(bannerList);
		//详情图
		imgMap.put("address", "1");
	    List<GoodsImagesDO> detailImgs = goodsImagesService.list(imgMap);
	    goodsGoods.setDetailImgs(detailImgs);
		
		String classId = goodsGoods.getClassId();
		model.addAttribute("goodsClass", goodsClassService.get(classId));

		//获取商品类型对应的参数信息
		List<GoodsTypeParamgDO> typeParamgList = goodsTypeParamgService.queryListAndValueByTypeId(goodsGoods.getTypeId());
		//获取商品类型对应的规格信息
		List<GoodsTypeSpecDO> typeSpecList = goodsTypeSpecService.queryListAndValueByTypeId(goodsGoods.getTypeId());
		*//*if(typeSpecList.size()<=0){
			Map<String, Object> par = new HashMap<>();
			par.put("goodsId", goodsGoods.getId());
			List<GoodsProductDO> list = goodsProductsService.list(par);
			if(list.size()>0){
			
					goodsGoods.setPriceF(list.get(0).getPriceF());
					goodsGoods.setPriceH(list.get(0).getPriceH());
					goodsGoods.setPriceL(list.get(0).getPriceL());
					goodsGoods.setPriceMarket(list.get(0).getPriceMarket());
					goodsGoods.setGoodsProduct(list.get(0));
				
			}
			
		}*//*
		model.addAttribute("goodsGoods", goodsGoods);
		//组装商品各类关联表数据
//				shopGoodsService.fetchLinks(obj, null, Cnd.orderBy().asc("location"));
//				List<Goods_product> productsList = obj.getProductList();
		model.addAttribute("specList", typeSpecList);
		model.addAttribute("typeParamgList", typeParamgList);
		model.addAttribute("typeList", goodsTypeService.queryAll());
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("goodsId", goodsGoods.getId());
		map.put("delFlag","0");
		model.addAttribute("productNum", goodsProductsService.count(map));
		List<GoodsProductDO> list =goodsProductsService.list(map);
		if(list.size()>0){
			for (GoodsProductDO goodsProductDO : list) {
				if(goodsProductDO.getIsDefault()==1){
					goodsGoods.setGoodsProduct(goodsProductDO);
				}
			}
		}else{
			GoodsProductDO goodsProductDO = new GoodsProductDO();
			goodsProductDO.setPostFee(new BigDecimal("0.00"));
			goodsGoods.setGoodsProduct(goodsProductDO);
		}
		
		model.addAttribute("productList", list);
		//在页面上显示商品类型管理的品牌
		//model.addAttribute("brandList", goodsBrandService.listByTypeId(goodsGoods.getTypeId()));

	    return "wx/goodsGoods/edit";
	}
	//上架/下架页面
	@GetMapping("/resetShelf/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String resetShelf(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
		model.addAttribute("goodsGoods", goodsGoods);
		return "wx/goodsGoods/reset_shelf";
	}

	//修改团品页面
	*//*@GetMapping("/resetGroup/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String resetGroup(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
		model.addAttribute("goodsGoods", goodsGoods);
		return "wx/goodsGoods/reset_group";
	}*//*
	//修改推荐商品页面
	@GetMapping("/resetRecommend/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String resetRecommend(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
		model.addAttribute("goodsGoods", goodsGoods);
		return "wx/goodsGoods/reset_recommend";
	}

	*//**
	 * 修改推荐商品
	 *
	 * @param
	 * @return
	 *//*
	@ResponseBody
	@PostMapping("/updateRecommend")
	public R updateRecommend(GoodsGoodsDO goods) {
		goodsGoodsService.update(goods);
		return R.ok();
	}

	//修改秒杀商品页面
//	@GetMapping("/resetSpike/{id}")
//	@RequiresPermissions("wx:goodsGoods:edit")
//	String resetSpike(@PathVariable("id") String id,Model model){
//		//获取商品信息
//		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
//		model.addAttribute("goodsGoods", goodsGoods);
//		return "wx/goodsGoods/reset_spike";
//	}

	*//**
	 * 保存
	 *//*
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:goodsGoods:add")
	public R save( GoodsGoodsDO goodsGoods, @RequestParam("products") String products,
				   @RequestParam("spec_values") String spec_values, //@RequestParam("prop_values") String prop_values,
				   @RequestParam("param_values") String param_values, @RequestParam("images") String images,
				   @RequestParam("imagesDetail") String imagesDetail){
		if(goodsGoods.getClassId()==null||"".equals(goodsGoods.getClassId())){
			return R.error("请选择分类");
		}
		if (goodsGoodsService.add(goodsGoods, products, spec_values,  param_values, images ,imagesDetail)>0){
			return R.ok();
		}
		return R.error();
	}
	*//**
	 * 修改
	 *//*
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:goodsGoods:edit")
	public R update( GoodsGoodsDO goodsGoods, @RequestParam("products") String products,
					 @RequestParam("spec_values") String spec_values, //@RequestParam("prop_values") String prop_values,
					 @RequestParam("param_values") String param_values, @RequestParam("images") String images,
					 @RequestParam("imagesDetail") String imagesDetail){
		if (goodsGoodsService.edit(goodsGoods, products, spec_values, param_values, images, imagesDetail)>0){
			return R.ok();
		}
		return R.error();
	}
	
	*//**
	 * 修改上下架
	 *//*
	@ResponseBody
	@RequestMapping("/updateShelf")
	@RequiresPermissions("wx:goodsGoods:edit")
	public R updateShelf( GoodsGoodsDO goodsGoods){
		if (goodsGoods.getDisabled()==0){
			goodsGoods.setUpAt(new Date());
		}else {
			goodsGoods.setDownAt(new Date());
		}
		if (goodsGoodsService.update(goodsGoods)>0){
			return R.ok();
		}
		return R.error();
	}
	
	*//**
	 * 删除
	 *//*
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:goodsGoods:remove")
	public R remove( String id){
		GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(id);
		goodsGoodsDO.setDelFlag(1);
		goodsGoodsDO.setGmtModified(new Date());
		if(goodsGoodsService.update(goodsGoodsDO)>0){
			return R.ok();
		}
		return R.error();
	}
	
	*//**
	 * 删除
	 *//*
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:goodsGoods:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
		for (String id : ids) {
			GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(id);
			goodsGoodsDO.setDelFlag(1);
			goodsGoodsDO.setGmtModified(new Date());
			goodsGoodsService.update(goodsGoodsDO);
		}
		return R.ok();
	}
	
	
	*//**
	 * 根据ID查询商品类型详情
	 *//*
	@ResponseBody
	@PostMapping("/getType")
	public R getType(@RequestParam("id") String id){
		GoodsTypeDO goodsTypeDO = goodsTypeService.get(id);
		return R.ok().put("data", goodsTypeDO);
	}

	*//**
	 * 通过商品类型获取品牌
	 *
	 * @param id
	 * @return
	 *//*
	@ResponseBody
	@PostMapping("/getBrand")
	public R getBrand(@RequestParam("id")String id) {
		List<GoodsTypeBrandDO> list = goodsTypeBrandService.queryAndBrandByTypeId(id);
//		shopGoodsTypeBrandService.fetchLinks(list, "brand", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	*//**
	 * 获取商品类型的扩展属性
	 *
	 * @param id
	 * @return
	 *//*
	@ResponseBody
	@PostMapping("/getProps")
	public R getProps(@RequestParam("id")String id) {
		List<GoodsTypePropsDO> list = goodsTypePropsService.queryListAndValueByTypeId(id);
//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	*//**
	 * 获取商品类型的详细参数
	 *
	 * @param id
	 * @return
	 *//*
	@ResponseBody
	@PostMapping("/getParam")
	public R getParam(@RequestParam("id")String id) {
		List<GoodsTypeParamgDO> list = goodsTypeParamgService.queryListAndValueByTypeId(id);
//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	*//**
	 * 获取商品分类及分类的商品类型
	 *
	 * @param id
	 * @return
	 *//*
	@ResponseBody
	@PostMapping("/getClass")
	public R getClass(@RequestParam("id")String id) {
//		List<GoodsClassDO> list = goodsClassService.queryAndTypeByTypeId(id);
		GoodsClassDO goodsClassDO = goodsClassService.get(id);
		if (goodsClassDO!=null){
			if("0".equals(goodsClassDO.getParentId())){
				return R.error("商品不能选择大类,请选择二级分类!");
			}

			GoodsTypeDO type =goodsTypeService.get(goodsClassDO.getTypeId());
			goodsClassDO.setGoodsType(type);
		}

//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", goodsClassDO);
	}


	*//**
	 * 开启规格页面
	 *
	 * @param id
	 * @param sku
	 *//*
	@GetMapping("/spec")
	public String spec(String id, String sku,String stock,String price,String priceA,String priceB,String priceC,String rebateOne,String rebateTwo,
					   String postFee,String weight,String type, Model model) {

		List<GoodsTypeSpecDO> typeSpecList = goodsTypeSpecService.queryListAndValueByTypeId(id);

		if (StringUtils.isEmpty(sku.trim())) {
			sku = goodsProductsService.getSkuPrefix();
		}
		model.addAttribute("price", price);
		model.addAttribute("priceA", priceA);
		model.addAttribute("priceB", priceB);
		model.addAttribute("priceC", priceC);
		model.addAttribute("sku", sku.toUpperCase());
		model.addAttribute("postFee", postFee);
		model.addAttribute("rebateOne", rebateOne);
		model.addAttribute("rebateTwo", rebateTwo);
		model.addAttribute("weight", weight);
		model.addAttribute("specList", typeSpecList);
		model.addAttribute("type", type);
		model.addAttribute("stock", stock);

//		model.addAttribute();
//		req.setAttribute("specList", typeSpecList);
//		req.setAttribute("lvList", memberLevelService.query(Cnd.orderBy().asc("point")));
		return "wx/goodsGoods/spec";
	}




	@ResponseBody
	@PostMapping("/upload")
	R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		String fileName = null;
//		fileName = FileUtil.renameToUUID(fileName);
//		GoodsImagesDO goodsImagesDO = new GoodsImagesDO("", "/files/" + fileName,0, new Date());
		try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image != null) {//如果image=null 表示上传的不是图片格式
//			    System.out.println(image.getWidth());//获取图片宽度，单位px
//			    System.out.println(image.getHeight());//获取图片高度，单位px
                fileName = "IMG_" + image.getWidth() + "_" + image.getHeight() + "@"+ UUID.randomUUID().toString();;
            }else {
                fileName = UUID.randomUUID().toString();
            }
//			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
			String imagePath = new ImgUpload(setImageUploadService).upload(file.getBytes(),
					fileName);
			return R.ok().put("data", imagePath);
		} catch (Exception e) {
			return R.error();
		}

	}
	*//**
	 * 所有商品ID和名字
	 *
	 * @param
	 * @return
	 *//*
	@ResponseBody
	@RequestMapping("/getGoods")
	public R getGoods() {
		List<Map<String,Object>> list = goodsGoodsService.queryAllForIdAndName(new HashMap<String,Object>());
//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	*//*查看商品评论*//*
	@GetMapping("/getComent/{id}")
	String getComent(@PathVariable("id") String id,Model model){
		model.addAttribute("goodsId", id);
		return "wx/goodsGoods/coment";
	}

	*//**
	 * 获取商品评论列表
	 *//*
	@ResponseBody
	@RequestMapping("/getComentList")
	public PageUtils getComentList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> comentList = orderComentService.getComentList(query);
		int total = orderComentService.getComentListCount(query);
		PageUtils pageUtils = new PageUtils(comentList, total);
		return pageUtils;
	}*/


}
